<script lang="ts" setup>
import type { VxeGridProps } from '#/adapter';
import { ref, onMounted } from 'vue';
import { Page, useVbenDrawer } from '@vben/common-ui';
import { Button, InputSearch, message, Popconfirm, Select, Modal } from 'ant-design-vue';
import { useVbenVxeGrid } from '#/adapter';
import { getProjectStageListApi, deleteProjectStageApi, getProjectStageDetailApi } from '#/api/project/stage';
import StageDrawer from './stage-drawer.vue';
import { getOptionsApi, type Option } from '#/api/core/optiontool';
import { $t } from '#/locales';

const [Drawer, drawerApi] = useVbenDrawer({
  connectedComponent: StageDrawer,
});

async function openDrawer(row?: any) {
  if (row?.id) {
    // 编辑模式：先调用后端接口获取详细数据
    try {
      const detailData = await getProjectStageDetailApi(row.id);
      drawerApi.setData(detailData);
    } catch (error) {
      console.error($t('stage.loadDetailFailed'), error);
      message.error($t('stage.loadDetailFailed'));
      return;
    }
  } else {
    // 新增模式：传递空对象
    drawerApi.setData({});
  }
  drawerApi.open();
}

interface StageType {
  id: string;
  name: string;
  description: string;
  startDate: string;
  endDate: string;
  status: string;
}

// 添加状态选项的响应式引用
const statusOptions = ref<Option[]>([]);

// 添加加载状态选项的函数
async function loadStatusOptions() {
  try {
    const data = await getOptionsApi({
      pathOrBeanName: 'com.matrix.app.common.enums.StageStatus'
    });
    statusOptions.value = data;
  } catch (error) {
    console.error($t('stage.loadStatusOptionsFailed'), error);
  }
}

const searchText = ref('');
const selectedRows = ref<StageType[]>([]);
const selectedStatus = ref('');

const gridOptions: VxeGridProps<StageType> = {
  columns: [
    { type: 'checkbox', width: 40 },
    { title: $t('common.seq'), type: 'seq', width: 50 },
    { field: 'name', title: $t('stage.name'), width: 200 },
    { field: 'memo', title: $t('stage.description') },
    { field: 'status', title: $t('stage.status'), width: 150 },
    {
      field: 'action',
      fixed: 'right',
      slots: { default: 'action' },
      title: $t('common.action.name'),
      width: 140,
    },
  ],
  height: 'auto',
  keepSource: true,
  pagerConfig: {},
  proxyConfig: {
    ajax: {
      query: async ({ page }) => {
        return await getProjectStageListApi({
          page: page.currentPage,
          pageSize: page.pageSize,
          searchKey: searchText.value,
          status: selectedStatus.value,
        });
      },
    },
  },
};

const [Grid, gridApi] = useVbenVxeGrid({ gridOptions });

async function handleDelete(row: any) {
  try {
    await deleteProjectStageApi(row.id);
    await gridApi.reload();
    message.success($t('common.action.deleteSuccess'));
  } catch {
    message.error($t('common.submit.failed'));
  }
}

function handleSave() {
  gridApi.reload();
}

function handleSearch() {
  gridApi.reload();
}

const gridEvents = {
  checkboxChange({ records }: { records: any[] }) {
    selectedRows.value = records;
  },
  checkboxAll({ records }: { records: any[] }) {
    selectedRows.value = records;
  },
};

async function handleDeleteSelected() {
  if (selectedRows.value.length === 0) return;

  Modal.confirm({
    title: $t('stage.delete.title'),
    content: $t('stage.delete.batchConfirm', { count: selectedRows.value.length }),
    okText: $t('common.yes'),
    cancelText: $t('common.no'),
    async onOk() {
      try {
        await Promise.all(selectedRows.value.map(row => deleteProjectStageApi(row.id)));
        selectedRows.value = [];
        await gridApi.reload();
        message.success($t('common.action.deleteSuccess'));
      } catch {
        message.error($t('common.submit.failed'));
      }
    }
  });
}

onMounted(() => {
  loadStatusOptions();
});
</script>

<template>
  <Page auto-content-height>
    <Drawer :on-save="handleSave" :status-options="statusOptions" />
    <Grid :grid-events="gridEvents">
      <template #toolbar-actions>
        <Button type="primary" @click="() => openDrawer()">
          {{ $t('common.action.add') }}
        </Button>
        <Button
          v-if="selectedRows.length > 0"
          class="ml-2"
          danger
          type="primary"
          @click="handleDeleteSelected"
        >
          {{ $t('common.action.delete') }}
        </Button>
      </template>
      <template #toolbar-tools>
        <div style="display: flex; align-items: center; gap: 12px;">
          <Select
            v-model:value="selectedStatus"
            :options="statusOptions"
            :placeholder="$t('stage.status')"
            style="width: 120px"
            allow-clear
            @change="handleSearch"
          />
          <InputSearch
            v-model:value="searchText"
            :placeholder="$t('common.search')"
            @search="handleSearch"
            style="width: 200px"
            allow-clear
          />
        </div>
      </template>
      <template #action="{ row }">
        <Button type="link" @click="() => openDrawer(row)">{{ $t('common.action.edit') }}</Button>
        <Popconfirm
          :title="$t('common.delete.confirm')"
          :ok-text="$t('common.yes')"
          :cancel-text="$t('common.no')"
          @confirm="async () => await handleDelete(row)"
        >
          <Button type="link" danger>{{ $t('common.action.delete') }}</Button>
        </Popconfirm>
      </template>
    </Grid>
  </Page>
</template>

<style scoped>
</style>
